from collections import defaultdict
from operator import index
import os
import requests
import json
import multiprocessing as mp
import shutil

from requests.packages import urllib3
urllib3.disable_warnings()


leetcodePath = "./Leetcode-Solution-All/"
targetPath = "docs/leetcode/"


readme_header = """---
icon: creative
sidebar: auto
---

# LeetCode题解汇总

因为题解较多，因此按照题号排序，每 100 道题汇总到一起。
你可以在侧边栏点击题号所处的范围，也可以通过 `Ctrl + F` 搜索题号/标题。

"""

header = """---
icon: page
title: {}
# 设置作者
author: 负雪明烛
# 设置写作时间
date: 2022-03-07
sidebar: false
category:
  - LeetCode
  - 算法题解
tag:
{}
---
"""


def genReadMe():
    solutions = os.listdir(leetcodePath)

    print(solutions)

    if not os.path.exists("leetcode-temp"):
        os.mkdir("leetcode-temp")

    if not os.path.exists(targetPath):
        os.mkdir(targetPath)


    with open(targetPath + "README.md", "w") as f:
        f.write(readme_header)

    indexes = defaultdict(list)

    for solu in solutions:
        if os.path.isdir(leetcodePath + solu) and not solu.startswith("."):
            print("solu", solu)
            for doc in os.listdir(leetcodePath + solu):
                problemId = doc.split(".")[0]
                fromPath =  leetcodePath + solu + "/" + doc
                endPath = "./leetcode-temp/" + problemId + ".md"
                shutil.copy(fromPath, endPath)
                indexes[solu].append([problemId, doc])

    cates = list(indexes.keys())
    print("cates", cates)
    cates.sort(key=lambda x : int(x.split("-")[0]))
    for cate in cates:
        with open(targetPath + "README.md", "a") as f:
            f.write("\n## " + cate + "\n")
        problems = indexes[cate]
        problems.sort(key=lambda x : int(x[0]))
        for probem in problems:
            with open(targetPath + "README.md", "a") as f:
                f.write("- [" + probem[1].replace(".md", "") + "](" + probem[0] + ".md)\n")


def deal(articlesPart):  # 这里是子进程
    for article in articlesPart:
        problemId = str(article.split(".")[0]).strip()
        print(problemId)
        res = requests.get("https://ojeveryday.com/api/AllProblem/getProblemByFrontendId?frontendId=" + problemId, verify=False)
        resJson = json.loads(res.content)
        title = problemId + ". " + resJson["title"] + " " +  resJson["translatedTitle"]
        tags = "  - {}\n".format(resJson["difficulty"]) + "\n".join(["  - " + tag for tag in resJson["topicTags"].split(",")])
        print(problemId, title, tags)
        with open("./leetcode-temp/" + article) as start:
            with open(targetPath + article, "w") as end:
                end.writelines(header.format(title, tags))
                end.writelines(start.readlines())

# 设置函数
# listTemp 为列表 平分后每份列表的的个数n
def splitList(listTemp, n):
    for i in range(0, len(listTemp), n):
        yield listTemp[i:i + n]

articles = os.listdir("./leetcode-temp/")


articlesParts = splitList(articles, 80)


if __name__ == '__main__':
    genReadMe()
    process = [mp.Process(target=deal, args=(articlesPart,)) for articlesPart in articlesParts]
    [p.start() for p in process]  # 开启了两个进程
    [p.join() for p in process]   # 等待两个进程依次结束
